package com.an.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.an.blog.admin.domain.BlogPhoto;
import com.an.blog.admin.domain.bo.BlogPhotoBo;
import com.an.blog.admin.domain.vo.BlogAlbumVo;
import com.an.blog.admin.domain.vo.BlogPhotoVo;
import com.an.blog.mapper.BlogAlbumMapper;
import com.an.blog.mapper.BlogPhotoMapper;
import com.an.blog.service.IBlogPhotoService;
import com.an.blog.utils.ConvertUtil;
import com.an.blog.web.domain.vo.BlogAlbumWebVo;
import com.an.blog.web.domain.vo.BlogPhotoWebVo;
import com.an.common.constant.BlogConstants;
import com.an.common.core.domain.BaseEntity;
import com.an.common.core.domain.PageQuery;
import com.an.common.core.page.TableDataInfo;
import com.an.common.utils.StringUtils;
import com.an.system.domain.vo.SysOssVo;
import com.an.system.service.ISysOssService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 相册图片Service业务层处理
 *
 * @author Ann
 * @date 2023-05-08
 */
@RequiredArgsConstructor
@Service
public class BlogPhotoServiceImpl implements IBlogPhotoService {

    private final ISysOssService ossService;
    private final BlogAlbumMapper albumMapper;
    private final BlogPhotoMapper baseMapper;

    /**
     * 查询相册图片
     */
    @Override
    public BlogPhotoVo queryById(Long photoId) {
        return baseMapper.selectVoById(photoId);
    }

    /**
     * 查询相册图片列表
     *
     * @param bo        业务对象
     * @param pageQuery 页面查询
     * @return {@link TableDataInfo }<{@link BlogPhotoVo }>
     * @author: Ann
     * @createDate: 2023/05/10 21:12:38
     * @version: 1.0.0
     */
    @Override
    public TableDataInfo<BlogPhotoVo> queryPageList(BlogPhotoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BlogPhoto> lqw = buildQueryWrapper(bo);
        Page<BlogPhotoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<BlogPhotoVo> records = result.getRecords();
        //ossId转换Map
        Map<Long, SysOssVo> sysOssVoMap = ConvertUtil
            .convert2OssIdSysOssMap(result.getRecords(), BlogPhotoVo::getPhotoImage);
        //albumId转换map
        Map<Long, BlogAlbumVo> blogAlbumVoMap = ConvertUtil
            .convertAlbumId2AlbumName(result.getRecords(), BlogPhotoVo::getAlbumId);
        records.forEach(record -> {
            //转换图片id为地址
            SysOssVo sysOssVo = sysOssVoMap.get(record.getPhotoImage());
            BlogAlbumVo blogAlbumVo = blogAlbumVoMap.get(record.getAlbumId());
            record.setPhotoImageUrl(sysOssVo != null ? sysOssVo.getUrl() : null);
            record.setAlbumName(blogAlbumVo != null ? blogAlbumVo.getAlbumName() : "");
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询相册图片列表
     */
    @Override
    public List<BlogPhotoVo> queryList(BlogPhotoBo bo) {
        LambdaQueryWrapper<BlogPhoto> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 建立查询包装
     *
     * @param bo 业务对象
     * @return {@link LambdaQueryWrapper }<{@link BlogPhoto }>
     * @author: Ann
     * @createDate: 2023/05/10 21:14:24
     * @version: 1.0.0
     */
    private LambdaQueryWrapper<BlogPhoto> buildQueryWrapper(BlogPhotoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BlogPhoto> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAlbumId() != null, BlogPhoto::getAlbumId, bo.getAlbumId());
        lqw.like(StringUtils.isNotBlank(bo.getPhotoDesc()), BlogPhoto::getPhotoDesc, bo.getPhotoDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), BlogPhoto::getStatus, bo.getStatus());
        lqw.between(params.get("beginTime") != null && params.get("endTime") != null,
            BaseEntity::getCreateTime, params.get("beginTime"), params.get("endTime"));
        lqw.orderByDesc(BlogPhoto::getPhotoId);
        return lqw;
    }

    /**
     * 新增相册图片
     *
     * @param bo 业务对象
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/06/26 09:42:15
     * @version: 1.0.0
     */
    @Override
    public Boolean insertByBo(BlogPhotoBo bo) {
        List<String> photoImages = StringUtils.splitList(bo.getPhotoImage(), ",");
        if (photoImages.size() > 1) {
            List<BlogPhoto> blogPhotos = photoImages.stream().map(photoImage -> {
                BlogPhoto blogPhoto = new BlogPhoto();
                blogPhoto.setPhotoDesc(bo.getPhotoDesc());
                blogPhoto.setPhotoImage(Long.valueOf(photoImage));
                blogPhoto.setAlbumId(bo.getAlbumId());
                return blogPhoto;
            }).collect(Collectors.toList());
            return baseMapper.insertBatch(blogPhotos);
        }
        BlogPhoto blogPhoto = BeanUtil.toBean(bo, BlogPhoto.class);
        return baseMapper.insert(blogPhoto) > 0;
    }

    /**
     * 修改相册图片
     */
    @Override
    public Boolean updateByBo(BlogPhotoBo bo) {
        BlogPhoto update = BeanUtil.toBean(bo, BlogPhoto.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BlogPhoto entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除相册图片
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 更新照片状态
     *
     * @param bo 业务对象
     * @return int
     * @author: Ann
     * @createDate: 2023/05/10 22:33:51
     * @version: 1.0.0
     */
    @Override
    public int updatePhotoStatus(BlogPhotoBo bo) {
        BlogPhoto blogPhoto = BeanUtil.toBean(bo, BlogPhoto.class);
        return baseMapper.updateById(blogPhoto);

    }

    /**
     * 存在
     *
     * @param ids id
     * @return {@link Boolean }
     * @author: Ann
     * @createDate: 2023/05/11 11:44:52
     * @version: 1.0.0
     */
    @Override
    public Boolean exist(Collection<Long> ids) {
        return baseMapper.exists(new LambdaQueryWrapper<BlogPhoto>()
            .in(CollUtil.isNotEmpty(ids), BlogPhoto::getAlbumId, ids));
    }

    /**
     * 查询页面列表
     *
     * @param albumId   相册id
     * @param pageQuery 页面查询
     * @return {@link TableDataInfo }<{@link BlogPhotoWebVo }>
     * @author: Ann
     * @createDate: 2023/06/26 17:01:35
     * @version: 1.0.0
     */
    @Override
    public TableDataInfo<BlogPhotoWebVo> queryWebPageList(Long albumId, PageQuery pageQuery) {
        BlogAlbumVo blogAlbumVo = albumMapper.selectVoById(albumId);
        BlogAlbumWebVo blogAlbumWebVo = BeanUtil.toBean(blogAlbumVo, BlogAlbumWebVo.class);
        Page<BlogPhoto> result = baseMapper.selectPage(pageQuery.build(),
            new LambdaQueryWrapper<BlogPhoto>().eq(BlogPhoto::getAlbumId, albumId)
                .eq(BlogPhoto::getStatus, BlogConstants.NORMAL).orderByDesc(BlogPhoto::getPhotoId));
        List<BlogPhoto> records = result.getRecords();
        long total = result.getTotal();
        List<BlogPhotoWebVo> blogPhotoWebVos = BeanUtil.copyToList(records, BlogPhotoWebVo.class);
        return TableDataInfo.build(blogPhotoWebVos, total, blogAlbumWebVo);
    }

}
